package com.atguigu.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author kabuda
 * @create 2022-12-08 19:23
 */
@Configuration
public class MyFeignConfig {
    @Bean("addHeaderRequestInterceptor")
    public RequestInterceptor addHeaderRequestInterceptor(){
        //匿名内部类，亦可直接创建此类再创建对象返回
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                System.out.println("RequestInterceptor："+Thread.currentThread().getId());
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if(requestAttributes!=null){
                    HttpServletRequest request = requestAttributes.getRequest(); //老请求：调用feign的请求
                    //获得老请求Cookie
                    String cookie = request.getHeader("Cookie");
                    //设置新请求Cookie
                    requestTemplate.header("Cookie",cookie);
                }

            }
        };
    }
}
